#include "TCPServer.h"
#include"Main/GateWay.h"
TCPServer::TCPServer(QObject *parent)
    : BasePort(parent)
{
    tcpServer = new QTcpServer(this);
    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newConnectionSlot()));
}



void TCPServer::setPortParam(PortStruct portParam)
{
    m_portParam = portParam;
    this->setObjectName(portParam.name());
}

void TCPServer::open()
{
    tcpServer->listen(QHostAddress::Any, m_portParam.port());
}

void TCPServer::close()
{
    for(int i=0; i<m_tcpClientList.size(); i++)//断开所有连接
    {
        m_tcpClientList[i]->disconnectFromHost();
        m_tcpClientList.removeAt(i);  //从保存的客户端列表中取去除
    }
    tcpServer->close();
}

void TCPServer::write(PortStruct target,QByteArray data)
{
     QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd");
    for(int i=0; i<m_tcpClientList.size(); i++)
    {
        if((m_tcpClientList[i]->peerAddress().toString() == target.ip()) && (m_tcpClientList[i]->peerPort() == target.port()))
        {
             m_tcpClientList[i]->write(data);
             qDebug()<<"Write-->"<<target<<"data:"<<DataTypeConver::formatString(data);
             Log::lock.lockForWrite();
             Log::writeToLog(time,"Write-->"+target.name()+" data: "+DataTypeConver::formatString(data));
             Log::lock.unlock();

             break;
        }
    }
}




/*********************************************
* @Name        newConnectionSlot
* @Funcyion    建立新TCP客户端与服务端连接
* @Param       NONE
* @Return      NONE
* @Other       槽函数
*********************************************/
void TCPServer::newConnectionSlot()
{
    QTcpSocket *tcpClient = tcpServer->nextPendingConnection();//与客户端通信的套接字
    m_tcpClientList.append(tcpClient);
    connect(tcpClient, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));
    connect(tcpClient, SIGNAL(disconnected()), this, SLOT(disconnectedSlot()));
    qDebug()<<"New TCP Client Connect,IP:"<<tcpClient->peerAddress().toString()<<",Port:"<<tcpClient->peerPort();

}

/*********************************************
* @Name        disconnectedSlot
* @Funcyion    TCP客户端与服务端断开连接时打印信息
* @Param       NONE
* @Return      NONE
* @Other       槽函数
*********************************************/
void TCPServer::disconnectedSlot()
{
    QTcpSocket *tcpClient = (QTcpSocket*)sender();//掉线对象
    for(int i=0; i<m_tcpClientList.size(); i++)
    {
        if(m_tcpClientList[i]->state() == QAbstractSocket::UnconnectedState)
        {
            m_tcpClientList.removeAt(i);
        }

    }
    PortStruct source;
    source.setIp(tcpClient->peerAddress().toString());
    source.setPort(tcpClient->peerPort());
    emit clientDisconnectedSignal(source);
    qDebug()<<tcpClient->peerAddress().toString()<<" has disconnected";//打印出掉线对象的ip
}

/*********************************************
* @Name        readyReadSlot
* @Funcyion    接收TCP服务器发送的数据，并压入接收队列
* @Param       NONE
* @Return      NONE
* @Other       NONE
*********************************************/
void TCPServer::readyReadSlot()
{
     QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd");
    QTcpSocket *tcpClient = (QTcpSocket*)sender();
    QByteArray data = tcpClient->readAll();

    PortStruct source;
    source.setType(m_portParam.type());
    source.setName(this->objectName());
    source.setIp(tcpClient->peerAddress().toString());
    source.setPort(tcpClient->peerPort());

    qDebug()<<"TCP Server runing now";
    emit receiveDataSignal(source,data);
    qDebug()<<"Read<-- "<<source<<"data:"<<DataTypeConver::formatString(data);

    Log::lock.lockForWrite();
    Log::writeToLog(time,"Read<--"+m_portParam.name()+" data: "+DataTypeConver::formatString(data));
    Log::lock.unlock();
}

TCPServer::~TCPServer()
{

}

